<template>
	<uni-card>
		<!-- 卡片头部 -->
		<template v-slot:title>
			<view class="title"><text class="index">{{questionNum}}</text> {{questionType}}</view>
		</template>
		<!-- 题名 -->
		<view class="questionTitle">{{detail.questionTitle}}</view>
		<!-- 代码 -->
		<uv-parse v-if="detail.codeFlag" :content="code"></uv-parse>
		<!-- 答案选项 -->
		<view class="questionOptions">
			<view class="item" :class="{'select': isSelected[index],'wrong-select':isWrongSelected[index] }"
				v-for="(item, index) in detail.questionOptions" :key="item.optionName" @click="handleAnswerClick(index)">
				<view class="name">{{item.optionName}}</view>
				<view class="value">{{item.optionValue}}</view>
			</view>
		</view>
		<!-- 题目切换 -->
		<view class="question-switch">
			<image @click="lastQuestionBtnClick" class="img" src="../../static/test-question/left_arrow.png"></image>
			<image @click="nextQuestionBtnClick" class="img" src="../../static/test-question/right_arrow.png"></image>
		</view>
		<!-- 答题情况 -->
		<view v-if="isReviewing" class="review-info">
			<!-- 答案展示 -->
			<view class="answer-info">
				<view class="left">
					<view class="tip">正确答案</view>
					<view class="answer">
						<text v-for="item in detail.questionAnswer" :key="item">{{item}}</text>
					</view>
				</view>
				<view class="divider"></view>
				<view v-if="!hide" class="right">
					<view class="tip">你的答案 </view>
					<view class="answer">
						<text v-for="item in detail.questionAnswer[currentIndex]" :key="item">{{item}}</text>
					</view>
				</view>
			</view>
			<!-- 答案难度、反馈、收藏 -->
			<view class="interact-info">
				<view class="rate">
					<view class="text">难度等级</view>
					<uni-rate allow-half readonly :value="detail.questionScore" />
				</view>
				<view class="feedback" @click="feedbackClick">
					<image class="img" src="../../static/test-question/feelback.png"></image>
					<view class="text">反馈</view>
				</view>
				<view class="collect" @click="collectClick">
					<image class="img" src="../../static/test-question/love.png"></image>
					<view class="text">{{detail.isCollect ? '取消收藏' : '收藏本题'}}</view>
				</view>
			</view>
			<!-- 答案解析和评论区的tabs页 -->
			<view class="tabs">
				<uni-segmented-control :current="currentTab" :values="['题目解析','讨论区']" @clickItem="onTabClick" styleType="text"
					activeColor="#627FFD"></uni-segmented-control>
				<view class="content">
					<view v-show="currentTab === 0">
						<view v-if="detail.questionTag?.length > 0" class="header">
							<view class="item">考点：</view>
							<uni-tag class="item" inverted :text="item" type="primary" v-for="item in detail.questionTag"
								:key="item" />
						</view>
						<view class="parse">
							<view v-for="item in detail.questionParse" :key="item.optionName">
								答案{{item.optionName}}:{{item.optionValue}}
							</view>
						</view>
					</view>
					<view v-show="currentTab === 1">
						评论区暂未开启
					</view>
				</view>
			</view>
		</view>
	</uni-card>
</template>

<script setup>
	import {
		computed,
		ref,
		watch
	} from "vue";

	const props = defineProps({
		hide: {
			type: Boolean,
			default: false
		},
		detail: {
			type: Object,
			default: () => ({
				"questionId": 1,
				"questionTitle": "在上述代码中，我们定义了一个函数，它接受一个数字作为参数。函数内部首先使用 toString() 方法将数字转换为字符串，然后使用",
				"questionCode": {
					"code": "var i = 0;\nfor (; i < 9; i++) {\n    console.log(i);\n    // more statements\n}\n\n"
				},
				"codeFlag": 1,
				"questionOptions": [{
						"optionName": "A",
						"optionValue": "打发发付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付付"
					},
					{
						"optionName": "B",
						"optionValue": "2"
					},
					{
						"optionName": "C",
						"optionValue": "3"
					},
					{
						"optionName": "D",
						"optionValue": "4"
					}
				],
				"questionAnswer": [
					"B"
				],
				"questionType": 1,
				"questionScore": 3,
				"questionParse": [{
						"optionName": "A",
						"optionValue": "2"
					},
					{
						"optionName": "B",
						"optionValue": "3"
					},
					{
						"optionName": "C",
						"optionValue": "1"
					},
					{
						"optionName": "D",
						"optionValue": "1"
					}
				],
				"questionTag": [
					"vue",
					"JavaScript"
				]
			})
		},
		currentIndex: {
			type: Number,
			default: 0
		},
		questionListParams: {
			type: Array,
			default: () => []
		},
		isReviewing: {
			type: Boolean,
			default: false
		},
		questionAnswer: {
			type: Array,
			default: () => []
		},
		getAnswer: {
			type: Function,
			default: () => {}
		}
	})

	const $emit = defineEmits(['getParams', 'lastClick', 'nextClick', 'feedbackBtnClick', 'collectClick'])

	// 用户选择的答案
	const userAnswer = ref([])
	// 各个答案是否被选中的状态
	const originValue = props.detail.questionOptions?.map(item => false)
	const isSelected = ref(originValue)
	// 答错的答案
	const isWrongSelected = ref([])
	// 当前tabs页
	const currentTab = ref(0)
	const params2 = ref([])

	// 计算出题号
	const questionNum = computed(() => {
		return (props.currentIndex + 1).toString().padStart(2, '0');
	})

	// 计算出题型
	const questionType = computed(() => {
		return props.detail.questionType === 0 ? '单选题' : props.detail.questionType === 1 ? '多选题' : '判断题'
	})

	// 计算出代码
	const code = computed(() => {
		const value = props.detail.questionCode?.code
		const TagValue = value?.replace(/\n/g, '</br>')
		// 原本的代码是带有' '，但是解析的时候解析不出来，要通过'&nbsp;'来代替一个空格
		const spaceValue = TagValue.replace(/ /g, '&nbsp;');
		return spaceValue
	})

	// 监听当前题目的改变,假如改变就初始化一下 答案选择情况
	watch(() => props.currentIndex, (newIndex) => {
		// console.log(props.questionAnswer, '答案列表', props.isReviewing, params2.value, newIndex);
		// 只要能进来执行代码说明切换题目了，先把原来的状态重置，如果有需要渲染的再渲染
		userAnswer.value = []
		isSelected.value = []
		isWrongSelected.value = []

		if (!props.isReviewing) {
			// 正在答题情况
			// 这是用户选的答案
			// const answers = props.questionListParams[newIndex]?.userAnswer
			const answers = props.getAnswer()[newIndex]?.userAnswer
			console.log('选择的答案', userAnswer.value);
			// 如果有长度说明已经答过题了，那么就渲染之前填写过的答案
			if (answers?.length > 0) {
				// console.log("渲染之前的答案");
				userAnswer.value = answers
				findSelectedIndex(answers, isSelected)
			}
		} else {
			// 解析答案的情况
			// 这是正确答案
			const answers = props.detail.questionAnswer
			findSelectedIndex(answers, isSelected)
			// 从用户选的答案找出错误的答案
			const isWrongAnswers = props.questionAnswer[props.currentIndex]?.filter(item => !answers.includes(item))
			findSelectedIndex(isWrongAnswers, isWrongSelected)
		}

	}, {
		immediate: true
	})

	// 封装一个方法找到查找答案所在的位置，并往某个对应的位置加上true标识
	function findSelectedIndex(from, selectedArr) {
		from?.forEach(item => {
			const index = props.detail.questionOptions?.findIndex(iitem => iitem.optionName === item)
			if (index !== -1) {
				selectedArr.value[index] = true
			}
		})
	}

	// 点击答案触发的回调
	const handleAnswerClick = (index) => {
		// 如果当前是题目解析的情况,不允许点击，直接跳出函数
		if (props.isReviewing) return
		// 多选题
		if (props.detail.questionType === 1) {
			isSelected.value[index] = !isSelected.value[index]
		} else {
			// 单选和判断题
			// 缓存状态
			const result = !isSelected.value[index]
			// 先将所有的改为false
			isSelected.value = isSelected.value.map(item => false)
			// 单独设置状态
			isSelected.value[index] = result
		}
		// 处理选中的答案
		const params = getParams()
		// userAnswer.value[props.currentIndex] = params.userAnswer
		console.log(params, 1111);
		$emit('getParams', params, props.currentIndex)
	}

	// 点击上一题和下一题
	const lastQuestionBtnClick = () => {
		$emit('lastClick')
	}
	const nextQuestionBtnClick = () => {
		$emit('nextClick')
	}

	// 暴将整理好的要提交的参数传出去
	const getParams = () => {
		// 1.处理选中的答案
		const answers = props.detail?.questionOptions.filter((item, index) => isSelected.value[index]).map(item => item
			.optionName)
		userAnswer.value = answers

		// 2.判断答案是否正确
		const isCorrect = isAnswerCorrect(answers)

		// 3.整理参数
		const params = {
			questionId: props.detail?.questionId,
			userAnswer: answers,
			isCorrect,
		}
		return params
	}

	// 判断答案是否正确
	const isAnswerCorrect = (answers) => {
		let isCorrect
		// 如果给的答案跟用户选择的答案个数不一样说明答案错误
		if (answers.length !== props.detail.questionAnswer?.length) {
			isCorrect = 0
			return isCorrect
		}
		// 答案个数一样的情况：
		for (let answer of answers) {
			// 遍历选中的每一个答案，看看在给出的正确答案里面能不能找到，假如有一个找不到那么答案就错误
			const result = props.detail.questionAnswer?.find(item => item !== answer)
			// 如果找到正确答案有，用户选的没有的，那么直接答错
			if (result) {
				isCorrect = 0
				return isCorrect
			}
		}
		// 如果上面两种情况都找不到错误的答案，那么说明答对了
		isCorrect = 1
		return isCorrect
	}

	// 反馈按钮
	const feedbackClick = () => {
		$emit('feedbackBtnClick')
	}

	// 收藏题目按钮
	const collectClick = () => {
		const oldCollect = props.detail.isCollect
		$emit('collectClick', oldCollect)
	}

	// 切换tab页面
	const onTabClick = (e) => {
		if (currentTab.value !== e.currentIndex) {
			currentTab.value = e.currentIndex;
		}
	}
</script>

<style lang="scss">
	.title {
		font-size: 26rpx;
		margin: 20rpx;
		color: $second-primary-color;

		.index {
			font-weight: 700;
		}
	}

	.questionTitle {
		font-weight: 700;
	}

	.questionOptions {
		.item {
			display: flex;
			align-items: center;
			margin: 40rpx 0;
			border-radius: 30rpx;

			.name {
				width: 70rpx;
				height: 70rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 50%;
				margin-right: 20rpx;
				background-color: #F6F6F5;
			}

			.value {
				flex: 1;
				font-size: 26rpx;
			}
		}

		.wrong-select {
			background-color: #F6F6F5;

			.name {
				color: #FFF;
				background-color: #FF8180;
			}
		}

		.select {
			background-color: #F6F6F5;

			.name {
				color: #FFF;
				background-color: $second-primary-color;
			}

			.value {}
		}


	}

	.question-switch {
		display: flex;
		justify-content: center;

		.img {
			width: 80rpx;
			height: 80rpx;
			margin: 0 40rpx;
		}
	}

	.review-info {
		.answer-info {
			display: flex;
			justify-content: space-evenly;
			align-items: center;
			background-color: #F6F6F6;
			padding: 20rpx 0;
			margin-top: 10rpx;
			border-radius: 16rpx;

			.left {
				text-align: center;

				.tip {
					color: $text-color;
					font-size: 26rpx;
				}

				.answer {
					color: $second-primary-color;
					font-weight: 700;
					font-size: 30rpx;
				}
			}

			.right {
				text-align: center;

				.tip {
					color: $text-color;
					font-size: 26rpx;
				}

				.answer {
					color: #FF8080;
					font-weight: 700;
					font-size: 30rpx;
				}
			}

			.divider {
				width: 4rpx;
				height: 40rpx;
				background-color: #ebe5df;
			}
		}

		.interact-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			color: $text-color;
			margin: 20rpx 0;

			.feedback,
			.collect {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin-top: 14rpx;

				.img {
					width: 50rpx;
					height: 50rpx;
				}
			}
		}

		.tabs {
			.content {
				.header {
					display: flex;
					flex-wrap: wrap;

					.item {
						margin: 0 10rpx 10rpx 0;
					}
				}
			}
		}
	}
</style>